<template>
  <!--会签管理-我的提交列表-工程项目合同审批弹窗-表单-->
  <a-spin :spinning="confirmLoading">
    <j-form-container class="scroll-view" style="height: 600px">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row style="margin-bottom: 20px;" v-if="pageType === 'add' || pageType === 'edit' || pageType === 'anew'">
          <a-col :span="24">
            <span style="font-size: 20px; font-weight: bold;">{{billsTemplateName}}</span>
          </a-col>
        </a-row>
        
        <template v-if="pageType === 'detail'">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="审批编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvNumber"
                style="margin-bottom: 10px;">
                <a-input :disabled="disabled" v-model="model.approvNumber" placeholder="请输入介绍"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="提交时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="submitTime"
                style="margin-bottom: 10px;">
                <j-date v-model="model.submitTime" :showTime="true" :disabled="disabled" date-format="YYYY-MM-DD"
                  style="width: 100%" placeholder="请选择提交时间"></j-date>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12">
              <a-form-model-item label="发起人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userName"
                style="margin-bottom: 10px;">
                <a-input :disabled="disabled" v-model="model.userName" placeholder="请输入发起人"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="post"
                style="margin-bottom: 10px;">
                <a-select :disabled="disabled" placeholder="请选择职位" v-model="model.post">
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col :span="12">
              <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId"
                style="margin-bottom: 10px;">
                <a-input :disabled="disabled" placeholder="请选择部门" v-model="model.departName">
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status"
                style="margin-bottom: 10px;">
                <a-select :disabled="disabled" placeholder="请选择状态" v-model="model.status">
                  <a-select-option value="0">未提交</a-select-option>
                  <a-select-option value="1">审核中</a-select-option>
                  <a-select-option value="2">已同意</a-select-option>
                  <a-select-option value="3">已驳回</a-select-option>
                  <a-select-option value="4">已撤销</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </template>
        
       <a-row>
         <a-col :span="12" v-if="pageType != 'anew'">
           <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName"
             style="margin-bottom: 10px;">
             <a-select :disabled="disabled" placeholder="请选择项目" :value="model.projectName"
               @change="handleChange('project',$event)">
               <a-select-option v-for="(item,index) in levelOneOptions" :key="index" :value="item">
                 {{item.label}}
               </a-select-option>
             </a-select>
           </a-form-model-item>
         </a-col>
         <a-col :span="12" v-if="pageType === 'anew'">
           <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectName"
             style="margin-bottom: 10px;">
             <a-select :disabled="true" placeholder="请选择项目" :value="model.projectName"
               @change="handleChange('project',$event)">
               <a-select-option v-for="(item,index) in levelOneOptions" :key="index" :value="item">
                 {{item.label}}
               </a-select-option>
             </a-select>
           </a-form-model-item>
         </a-col>
         <a-col :span="12" v-if="pageType === 'add' || pageType === 'edit' || pageType === 'anew'">
           <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departName" style="margin-bottom: 10px;">
             <a-select :disabled="disabled"  placeholder="请选择申请部门" :value="model.departName" @change="handleChange('depart',$event)">
               <a-select-option v-for="(item,index) in departList" :key="index" :value="item">
                     {{item.label}}
                   </a-select-option>
             </a-select>
           </a-form-model-item>
         </a-col>
         <a-col :span="12" v-if="pageType === 'detail' || pageType === 'approver' || pageType === 'history'">
           <a-form-model-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startTime"
             style="margin-bottom: 10px;">
             <a-date-picker :disabled="disabled" placeholder="请选择开始日期" format="YYYY-MM-DD" v-model="model.startTime" style="width:100%;" />
           </a-form-model-item>
         </a-col>
       </a-row>
       
       <a-row>
         <a-col :span="12">
           <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.title" placeholder="请输入标题"></a-input>
           </a-form-model-item>
         </a-col>
         <a-col :span="12">
           <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.name" placeholder="请输入合同名称"></a-input>
           </a-form-model-item>
         </a-col>
       </a-row>
       
       <a-row>
         <a-col :span="12">
           <a-form-model-item label="合同期限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deadline"
             style="margin-bottom: 10px;">
             <div style="display: flex;align-items: center;">
               <a-input style="width: calc(100% - 40px);" :disabled="disabled" v-model="model.deadline" placeholder="请输入合同期限"></a-input><div style="width: 40px;">个月</div>
             </div>
           </a-form-model-item>
         </a-col>
         <a-col :span="12">
           <a-form-model-item label="合同份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.number" placeholder="请输入合同份数"></a-input>
           </a-form-model-item>
         </a-col>
       </a-row>
       
       <a-row>
         <a-col :span="12">
           <a-form-model-item label="对方单位名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="other"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.other" placeholder="请输入对方单位名称"></a-input>
           </a-form-model-item>
         </a-col>
         <a-col :span="12">
           <a-form-model-item label="合同金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="money"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.money" placeholder="请输入合同金额"></a-input>
           </a-form-model-item>
         </a-col>
       </a-row>
       
       <a-row>
         <a-col :span="12">
           <a-form-model-item label="对方单位地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherAddress"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.otherAddress" placeholder="请输入对方单位地址"></a-input>
           </a-form-model-item>
         </a-col>
         <a-col :span="12">
           <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractNumber"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.contractNumber" placeholder="请输入合同编号"></a-input>
           </a-form-model-item>
         </a-col>
       </a-row>
       
       <a-row>
         <a-col :span="12">
           <a-form-model-item label="对方单位电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherPhone"
             style="margin-bottom: 10px;">
             <a-input :disabled="disabled" v-model="model.otherPhone" placeholder="请输入对方单位电话"></a-input>
           </a-form-model-item>
         </a-col>
         <a-col :span="12" v-if="pageType === 'add' || pageType === 'edit' || pageType === 'anew'">
           <a-form-model-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startTime"
             style="margin-bottom: 10px;">
             <a-date-picker :disabled="disabled" placeholder="请选择开始日期" format="YYYY-MM-DD" v-model="model.startTime" style="width:100%;" />
           </a-form-model-item>
         </a-col>
       </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="合同备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark"
              style="margin-bottom: 10px;margin-left: 20px;">
              <div style="position: relative;">
                <textarea :disabled="disabled" v-model="model.remark" cols="100" rows="3" style="width: 93%;padding-right: 30px;line-height: 25px;" maxlength="500"
                  placeholder="请输入合同备注"></textarea>
                  <div style="position: absolute;right: 64px;bottom: 20px;font-size: 12px;">{{model.remark.length}}/500</div>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
        
        <a-row>
          <a-col :span="pageType === 'add' ? 12 : 24">
            <a-form-model-item label="合同协议附件" :labelCol="pageType === 'add'?labelCol:labelCol2" :wrapperCol="pageType === 'add'?wrapperCol:wrapperCol2" prop="attachment"
              :style="{margin: pageType === 'add'?'0 0 10px 0':'0 60px 10px 20px'}">
              <j-upload v-model="model.attachment" :disabled="disabled" :buttonVisible="!disabled"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="pageType === 'add'">
            <div style="display: flex;justify-content: space-between;align-items: center;margin-right: 40px;">
              <div style="line-height: 20px;color: red;" v-if="billsTemplateName == '非工程类合同审批'">1.请附对方营业执照、资质证书等相关材料。</div>
              <div style="line-height: 20px;color: red;" v-else>1.请附会签完成的询价单；<br />2.请附对方营业执照、资质证书等相关材料。</div>
              <a-button @click="downfile" type="primary">下载合同模板</a-button>
            </div>
          </a-col>
        </a-row>

        <a-row v-if="pageType === 'detail' || pageType === 'approver' || pageType === 'history'">
          <a-form-model-item label="审核流程" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark"
            style="margin-bottom: 10px;margin-left: 20px;">
            <app-flow :list="list" :pageType="pageType" :approver="approver"></app-flow>
          </a-form-model-item>
        </a-row>
        
        <a-row v-if="!(pageType === 'approver'?false:true)">
          <a-button style="background: orange;color: white;border:1px solid orange;margin-left: 118px;"
            @click="handleOpen('history')">查看原审核记录</a-button>
        </a-row>

      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import {
    httpAction,
    getAction
  } from '@/api/manage'
  import {
    validateDuplicateValue
  } from '@/utils/util'
  import appFlow from '../components/appFlow.vue'
  export default {
    name: 'WtBrandForm',
    components: { appFlow },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: true,
        required: false,
      },
      pageType: {
        type: String,
        default: '', //add-新增 anew-重复提交 edit-编辑 detail-详情 approver-审批
      },
      billsTemplateName:{
        type: String,
        default: '',
      },
      defaultModel: {
        type: Boolean,
        default () {
          return {

          }
        },
      }
    },
    data() {
      return {
        title: '',
        model: {
          title: '',
          projectId: '',
          projectName: '',
          departId: '',
          departName: '',
          name: '',
          number: '',
          deadline: '',
          startTime:'',
          money: '',
          contractNumber: '',
          other: '',
          otherAddress: '',
          otherPhone: '',
          status: '',
          remark: '',
          status: '',
          attachment: '',
        },
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },
        labelCol2: {
          xs: {
            span: 24
          },
          sm: {
            span: 2
          },
        },
        wrapperCol2: {
          xs: {
            span: 24
          },
          sm: {
            span: 22
          },
        },
        confirmLoading: false,
        validatorRules: {},
        levelOneOptions: [],
        departList: [], //部门列表
        countersignTemplateId: '',
        list: [],
        url: {
          detail: '/countersign/wtCountersignProjectContract/queryByCountersignId',
          add: '/countersign/wtCountersignProjectContract/add',
          edit: '/countersign/wtCountersignProjectContract/edit',
          anew: '/countersign/wtCountersignProjectContract/editSubmit',
          approver: '/countersign/wtCountersignProcess/submitExamineApprove',
        },
        approver:'',
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    created() {
      if (!!window.localStorage.getItem("pro__Login_Userinfo")) {
        let userInfo = JSON.parse(window.localStorage.getItem("pro__Login_Userinfo")).value;
        this.approver = userInfo.id;
      }
      if (!!window.localStorage.getItem("pro__USER_DEPARTLIST")) {
        let departList = JSON.parse(window.localStorage.getItem("pro__USER_DEPARTLIST")).value;
        if (departList && departList.length > 0) {
          this.departList = departList.map((ite) => ({
            ...ite,
            value: ite.id,
            label: ite.departName
          }))
        }
      }
      //验证表单
      if (this.pageType === 'add' || this.pageType === 'edit' || this.pageType === 'anew') {
        this.validatorRules = {
          projectName: [{
            required: true,
            message: '项目不能为空,请选择~',
            trigger: 'change'
          }],
          departName: [{
            required: true,
            message: '申请部门不能为空,请选择~',
            trigger: 'change'
          }],
          title: [{
            required: true,
            message: '标题不能为空,请输入~',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '合同名称不能为空,请输入~',
            trigger: 'blur'
          }],
          other: [{
            required: true,
            message: '对方单位名称不能为空,请输入~',
            trigger: 'blur'
          }],
          money: [{
            required: true,
            message: '合同金额不能为空,请输入~',
            trigger: 'blur'
          }],
          attachment:[{
            required: true,
            message: '合同协议附件不能为空,请上传~',
            trigger: 'blur'
          }],
        }
      };
      if(this.pageType === 'add'){
        this.Dict();
      }
    },
    mounted() {
      if (!!this.defaultModel.id) {
        this.model = JSON.parse(JSON.stringify(this.defaultModel));
        this.list = this.model.list;
        if (this.levelOneOptions && this.levelOneOptions.length > 0) {
          let info = this.levelOneOptions.find((item) => item.departName == this.model.projectName)
          this.model.projectId = info.id
        }
        if (this.departList && this.departList.length > 0) {
          let info = this.departList.find((item) => item.departName == this.model.departName)
          this.model.departId = info.id
        }
        this.$forceUpdate();
      }
    },
    methods: {
      //下拉选择
      handleChange(type, item) {
        console.log(1, type, item);
        if (type === 'project') {
          this.model.projectName = item.label;
          this.model.projectId = item.value;
        } else if(type === 'depart'){
          this.model.departName = item.label;
          this.model.departId = item.value;
        }
      },
      //获取数据字典
      Dict(record) {
        //项目列表
        //getAction(`/sys/sysDepart/getDepartByOrgType?orgType=1`).then((res) => {
        getAction(`/countersign/wtCountersignTemplate/getProjectListBybillsTemplateName?billsTemplateName=${this.billsTemplateName}`).then((res) => {
          if (res.success) {
            let treeList = res.result;
            if (treeList && treeList.length > 0) {
              this.levelOneOptions = [...treeList].map((v) => {
                return {
                  ...v,
                  value: v.id,
                  label: v.departName,
                }
              })
            }
            if (this.pageType === 'edit' || this.pageType === 'anew' || this.pageType === 'detail' || this.pageType === 'approver') {
              if(!!record){
                this.getdata(record);
              }
            }
            this.$forceUpdate();
          }
        })
      },
      //获取数据
      getdata(record) {
        var that = this
        getAction(`/countersign/wtCountersignProjectContract/queryByCountersignId?countersignId=${record.id}`).then(
          (res) => {
            if (res.success) {
              this.model = res.result;
              this.list = res.result.list;
              if (this.levelOneOptions && this.levelOneOptions.length > 0) {
                let info = this.levelOneOptions.find((item) => item.departName == this.model.projectName)
                this.model.projectId = info.id
              }
              if (this.departList && this.departList.length > 0) {
                let info = this.departList.find((item) => item.departName == this.model.departName)
                console.log(2, info)
                if(!!info){
                   this.model.departId = info.id
                }
              }
            }
          }
        )
      },
      add(record) {
        this.countersignTemplateId = record.id;
      },
      edit(record) {
        if (this.pageType === 'edit' || this.pageType === 'anew' || this.pageType === 'detail' || this.pageType ===
          'approver') {
          this.Dict(record);
        }
      },
      //查看原审核记录
      handleOpen(type) {
        this.$emit('handleOpen', type);
      },
      submitForm(record) {
        const _self = this
        if (this.pageType === 'add' || this.pageType === 'edit' || this.pageType === 'anew') {
          if (!this.model.projectId) {
            _self.$message.warning('项目不能为空,请选择');
            return;
          }
          if (!this.model.departId) {
            _self.$message.warning('申请部门不能为空,请选择');
            return;
          }
          if (!this.model.title) {
            _self.$message.warning('标题不能为空,请选择');
            return;
          }
          if (!this.model.name) {
            _self.$message.warning('合同名称不能为空,请输入');
            return;
          }
          if (!this.model.other) {
            _self.$message.warning('对方单位名称不能为空,请输入');
            return;
          }
          if (!this.model.money) {
            _self.$message.warning('合同金额不能为空,请输入');
            return;
          }
          if (!this.model.attachment) {
            _self.$message.warning('附件资料不能为空,请上传');
            return;
          }
        }
        _self.model.billsTemplateName = this.billsTemplateName;
        let params = {};
        let httpurl = ''
        if (_self.pageType === 'add') {
          httpurl = _self.url.add;
          _self.model.countersignTemplateId = this.countersignTemplateId;
          params = _self.model;
        } else if (_self.pageType === 'edit') {
          httpurl = _self.url.edit;
          params = _self.model;
        } else if (_self.pageType === 'anew') {
          httpurl = _self.url.anew;
          params = _self.model;
        } else if (_self.pageType === 'approver') {
          httpurl = _self.url.approver;
          if (this.list && this.list.length > 0) {
            this.list.forEach(ite => {
              if (this.approver === ite.approver && ite.status === '1') {
                params.feedback = ite.feedback;
                params.ideaAttachment = ite.ideaAttachment;
                params.id = ite.id;
              }
            })
          }
          if (!params.feedback) {
            _self.$message.warning('审批意见不能为空,请填写');
            return;
          }
        }
        // 触发表单验证
        _self.confirmLoading = true;
        params.status = record;
        console.log('提交表单', params)
        // debugger
        httpAction(httpurl, params, 'POST')
          .then((res) => {
            if (res.success) {
              _self.$message.success(res.message)
              _self.$emit('ok')
            } else {
              _self.$message.warning(res.message)
            }
          })
          .finally(() => {
            _self.confirmLoading = false
          })
      },
    },
  }
</script>
<style scoped>
  .scroll-view {
    overflow: auto;
    overflow-y: scroll;
  }
</style>